package com.dhcc.bpm.modules.scf.controller;


import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.StringUtils;
import com.dhcc.bpm.modules.scf.dto.ScfSinoiovDTO;
import com.openapi.sdk.service.DataExchangeService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 中交视图控制器类
 */
@Slf4j
@Api(value = "中交视图相关", tags = "中交视图相关接口")
@RestController
@RequestMapping("/view")
public class ViewInterfaceController {


    @Value("${sinoiov.url}")
    private String url;
    @Value("${sinoiov.srt}")
    private String srt;
    @Value("${sinoiov.clientId}")
    private String clientId;


    /**
     * @param type type类型  运输节点服务 transportManage  运输行程服务 pathTrack
     * @return 返回中交提供url插件
     */
    @GetMapping("/sinoiov")
    @ApiLog("获取中交插件接口")
    @Log(title = "获取中交插件接口", businessType = BusinessType.SELECT)
    public R sinoiov(ScfSinoiovDTO dto) {
        Map<String, String> map = new HashMap<String, String>(3);
        map.put("cid", clientId);
        //私钥用于 SDK 生成签名，不会在请求中传输
        map.put("srt", srt);
        map.put("type", dto.getType());

        if (StringUtils.isNotEmpty(dto.getVclN())) {
            String pluginParams = "{\"vclN\":\"%s\",\"vco\":%s,\"qryBtm\":\"%s\",\"qryEtm\":\"%s\"}";

            String formattedString = String.format(pluginParams, dto.getVclN(), dto.getVco(), dto.getQryBtm(), dto.getQryEtm());

//        String  pluginParams ="{\"vclN\":\"桂N86736\",\"vco\":2,\"qryBtm\":\"2023-12-19 17:29:09\",\"qryEtm\":\"2023-12-20 17:29:09\"}";
            map.put("pluginParams", formattedString);
        }


        log.info("======请求中交地址======:{}", url);
        log.info("======请求中交参数======:{}", map);
        String res = null;
        try {
            DataExchangeService des = new DataExchangeService(5000, 8000);
            // 通过https方式调用!此方法内部会使用私钥生成签名参数 sign,私钥不会发送
            res = des.postHttps(url, map);
        } catch (Exception e) {
            log.error("======请求中交接口失败======", e);
        }
        log.info("======请求中交返回参数======:{}", res);
        return R.data(res);
    }

    @GetMapping("/customMap")
    @ApiLog("获取中交接口")
    @Log(title = "中交视图接口", businessType = BusinessType.SELECT)
    public R customMap(ScfSinoiovDTO dto) {
        if (dto.getVclN() == null || dto.getQryBtm() == null) {
            return R.data("参数不完整");
        }
        String result = "http://www.lvlianhengsheng.com:8080?vclN=" + dto.getVclN() + "&vco=" + dto.getVco() + "&qryBtm=" + dto.getQryBtm() + "&qryEtm=" + dto.getQryEtm();
        result = encodeUrl(result);


        return R.data(result);
    }


    public static String encodeUrl(String url) {
        try {
            // 将时间参数进行URL编码
            String[] parts = url.split("\\?");
            String baseUrl = parts[0];
            String queryString = parts[1];
            String[] params = queryString.split("&");
            StringBuilder encodedQueryString = new StringBuilder();
            for (String param : params) {
                if (param.startsWith("qryBtm=") || param.startsWith("qryEtm=")) {
                    String[] keyValue = param.split("=");
                    String encodedValue = URLEncoder.encode(keyValue[1], "UTF-8");
                    encodedQueryString.append(keyValue[0]).append("=").append(encodedValue).append("&");
                } else {
                    encodedQueryString.append(param).append("&");
                }
            }
            encodedQueryString.deleteCharAt(encodedQueryString.length() - 1); // 删除末尾的"&"
            return baseUrl + "?" + encodedQueryString.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return url; // 如果编码失败，返回原始URL
        }
    }

    public static void main(String[] args) {

        System.out.println(StringUtils.isNotEmpty("1"));
        System.exit(1);

        String firstName = "John";
        String lastName = "Doe";
        int age = 30;

        String pluginParams = "{\"vclN\":\"%s\",\"vco\":%s,\"qryBtm\":\"%s\",\"qryEtm\":\"%s\"}";

        String formattedString = String.format(pluginParams, firstName, lastName, age, "123");
        System.out.println(formattedString);


    }
}
